<?php
/**
 * Created by PhpStorm.
 * User: lelouchms
 * Date: 2019/5/6
 * Time: 17:24
 */

namespace app\index\controller;


use app\backend\controller\BackendController;
use app\common\exception\CustomerException;
use app\common\library\JWTToken;
use app\common\library\RequestUtil;
use app\common\model\User;
use app\common\util\CommonUtil;
use think\facade\Env;

class Auth extends Base
{

    const APP_KEY = "wxe5a1d12b59ac69c4";

    const  APP_SECRET = "a37747d1a045bbf62be9aeb3c357fdcd";

    const OAUTH_URL = "https://api.weixin.qq.com/sns/jscode2session";

    public function initialize()
    {
        $this->allow_action = ["login", "registerUser"];
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * 用户登陆
     * @param $code
     * @return array
     * @throws CustomerException
     */
    public function login($code)
    {
        $oauthResponse = RequestUtil::getInstance()->sendRequest(self::OAUTH_URL, [
            "appid" => self::APP_KEY,
            "secret" => self::APP_SECRET,
            "js_code" => $code,
            "grant_type" => "authorization_code"
        ]);
        $oauthResponse = json_decode($oauthResponse, true);
        if (!empty($oauthResponse['errcode'])) {
            throw new CustomerException($oauthResponse['errmsg']);
        }
        session("oauth_data", [
            'openid' => $oauthResponse['openid'],
            'session_key' => $oauthResponse['session_key'],
        ]);
        $userModel = new User();
        $webUser = $userModel->findByOpenId($oauthResponse['openid']);
        if (empty($webUser)) {
            throw new CustomerException("用户尚未注册", 10001);
        }
        $webUser['token'] = (string)JWTToken::getToken($webUser["id"], "api-web-user");
        $webUser->save();
        session("web_user", $webUser);
        return [
            'id' => $webUser['id'],
            'avatar' => $webUser['wx_avatar'],
            'wx_avatar' => $webUser['wx_avatar'],
            'access_token' => $webUser['token'],
            'type' => $webUser['type']
        ];
    }

    /**
     * 用户注册
     * @param $rawData
     * @param $signature
     * @return array
     * @throws CustomerException
     */
    public function registerUser($rawData, $signature)
    {
        $oauthData = session("oauth_data");
        if (empty($oauthData)) throw new CustomerException("请先登录");
        if (empty($signature)) throw new CustomerException("缺少参数signature");
        if (empty($rawData)) throw new CustomerException("缺少参数rawData");
        if ($signature !== sha1($rawData . $oauthData['session_key'])) throw new CustomerException("签名校验失败");
        $rawData = json_decode($rawData, true);
        $userModel = new User();
        $findUser = $userModel->findByOpenId($oauthData['openid']);
        if (!empty($findUser)) throw new CustomerException("该用户已注册", 10002);
        $webUser = [
            "nickname" => $rawData['nickName'],
            "avatar" => Env::get("common.default_avatar"),
            "wx_avatar" => $rawData['avatarUrl'],
            "open_id" => $oauthData["openid"],
            "type" => 1,
            "create_time" => date("Y-m-d H:i:s"),
            "remark" => "用户"
        ];
        $webUser['id'] = $userModel->insert($webUser, false, true);
        $webUser['token'] = (string)JWTToken::getToken($webUser["id"], "api-web-user");
        $userModel->update($webUser);
        return [
            'id' => $webUser['id'],
            'avatar' => CommonUtil::formatHostUrl($webUser['avatar']),
            'wx_avatar' => $webUser['wx_avatar'],
            'access_token' => $webUser['token'],
            'type' => $webUser['type']
        ];
    }

    public function logout()
    {
        session("web_user", null);
        session("oauth_data", null);
        return "退出成功";
    }


    public function _empty()
    {
        throw new CustomerException("无效的地址");
    }

}